#coding=utf-8
import datetime
from elixir import *

class FInstrument(Entity):
    using_options(tablename='finstruments')
    
    code = Field( String(20),  unique=True )
    name = Field( String(50),  unique=True )
    ipo = Field(Date)
    
    tds = OneToMany('TradeDay') 
    def __init__(self, code=None, name=None, ipo=None):
        self.code = code
        self.name = name
        self.ipo = ipo
    
    def __str__(self):
        if type( self.code ).__name__ == 'unicode':
            code = self.code.encode('utf8')
            
        if type( self.name ).__name__ == 'unicode':
            name = self.name.encode('utf8')
        
        return '%s:%s'%(code, name)
        
    __repr__  = __str__
            
    def td_on(self, dt):pass
    def tds_between(self, st, ed):pass
    def tds_since(self, st):pass
    
class SIndex(FInstrument):
    using_options(tablename='sindexes', inheritance='multi')
    
class Stock(FInstrument):
    using_options(tablename='stocks', inheritance='multi')
    
    ipo_price = Field(Float)
    market = Field( String(50) )
    
    tss = OneToMany('TradableShare')
    
    def __init__(self, code=None, name=None, ipo=None, ipo_price=None, market=None):
        FInstrument.__init__(self, code, name, ipo)
        self.ipo_price = ipo_price
        self.market = market
    
    def get_ts(self, date=None):
        '''股票某一日期的可流通股份数量'''
        if not date:
            date = datetime.date.today().isoformat()    
        for ts in self.tss:
            if date >= ts.beginning.isoformat():
                return ts.quantity                
    ts = property(fget=get_ts)
        
class Fund(FInstrument):
    using_options(tablename='funds', inheritance='multi')

class Warrent(FInstrument):
    using_options(tablename='warrents', inheritance='multi')    
    
